import React, { useState, useEffect, useRef, useLayoutEffect } from 'react'; // 这行必须写，不然报错，可能是eslint搞事情。
import {
  Row,
  Input,
  Form,
  DatePicker,
  Modal,
  message,
  TreeSelect,
  Radio,
  Select,
  InputNumber,
  Tree,
} from 'antd';
const { confirm } = Modal;
const { RangePicker } = DatePicker;
const { TreeNode } = TreeSelect;
const { Option } = Select;
const { TextArea } = Input;
import { roleMenuTreeselect, deeps, treeselect } from '@/api/system/menu.js';
import { getRole, updateRole } from '@/api/system/role.js';
const EditroleModalForm = ({
  visible,
  onhideRoleModal,
  onCancel,
  oninitList,
  roleId,
}) => {
  const [form] = Form.useForm();
  useResetFormOnCloseModal({
    form,
    visible,
  });

  const [radio, setRadio] = useState(0);
  const [treeData, settreeData] = useState([]);
  const [checkedKeys, setCheckedKeys] = useState([]);
  const [initValues, setinitValues] = useState(null);

  useEffect(() => {
    getRoles();
    getMenuTreeselectCheckedKeys();
  }, [roleId]);

  //点击添加用户
  const onOk = () => {
    form.submit();
  };

  const onConcle = () => {
    console.log(onCancel, visible);
  };

  //表单提交方法
  const onFinish = values => {
    //菜单选择赋值
    values.menuIds = checkedKeys;
    values.roleId = roleId;

    updateRole(values).then(res => {
      if (res.code == 200) {
        message.success('修改角色成功');
        onhideRoleModal();
        oninitList();
      } else if (res.code == 500) {
        message.warning(res.msg);
      }
    });
  };

  //获取回显菜单值
  const getMenuTreeselectCheckedKeys = () => {
    roleMenuTreeselect(roleId).then(res => {
      if (res.code == 200) {
        settreeData(deeps(res.menus));
        setCheckedKeys(res.checkedKeys);
      }
    });
  };

  //角色节点树选择
  const onCheck = checkedKeys => {
    setCheckedKeys(checkedKeys);
  };

  //获取角色详细信息
  const getRoles = () => {
    getRole(roleId).then(res => {
      if (res.code == 200) {
        setinitValues(res.data);
      }
    });
  };

  const layout = {
    labelCol: { span: 6 },
    wrapperCol: { span: 16 },
  };

  return (
    <Modal
      title="修改角色"
      visible={visible}
      onOk={onOk}
      onCancel={onCancel}
      cancelText="取消"
      okText="确定"
      style={{
        width: '300px !important',
        padding: '30px 20px',
        color: '#606266',
        fontSize: '14px',
        wordBreak: 'break-all',
      }}
    >
      {initValues !== null && (
        <Form
          {...layout}
          form={form}
          layout="horizontal"
          labelAlign="right"
          onFinish={onFinish}
          initialValues={initValues}
        >
          <Form.Item
            name="roleName"
            label="角色名称"
            rules={[{ required: true, message: '角色名称不能为空' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="roleKey"
            label="权限字符"
            rules={[{ required: true, message: '权限字符不能为空' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item name="roleSort" label="角色顺序">
            <InputNumber min={0} />
          </Form.Item>
          <Form.Item name="status" label="状态">
            <Radio.Group>
              <Radio value={'0'}>正常</Radio>
              <Radio value={'1'}>停用</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item name="menuIds" label="菜单权限">
            {treeData.length && (
              <Tree
                treeData={treeData}
                checkable
                onCheck={onCheck}
                checkedKeys={checkedKeys}
              ></Tree>
            )}
          </Form.Item>
          <Form.Item name="remark" label="备注">
            <TextArea rows={4} />
          </Form.Item>
        </Form>
      )}
    </Modal>
  );
};
// reset form fields when modal is form, closed
const useResetFormOnCloseModal = ({ form, visible }) => {
  const prevVisibleRef = useRef();
  useEffect(() => {
    prevVisibleRef.current = visible;
  }, [visible]);
  const prevVisible = prevVisibleRef.current;
  useEffect(() => {
    if (!visible && prevVisible) {
      form.resetFields();
    }
  }, [visible]);
};

export default EditroleModalForm;
